package com.dongdong.bookstore.module.pms.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dongdong.bookstore.common.api.CommonPage;
import com.dongdong.bookstore.common.exception.Asserts;
import com.dongdong.bookstore.module.pms.dto.BookCategoryDto;
import com.dongdong.bookstore.module.pms.dto.BookDto;
import com.dongdong.bookstore.module.pms.model.Book;
import com.dongdong.bookstore.module.pms.model.BookCategory;
import com.dongdong.bookstore.module.pms.service.BookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import org.apache.ibatis.annotations.Param;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 书籍  前端控制器
 * </p>
 *
 * @author chiangkai
 * @since 2021-11-07
 */
@Api(tags = "书籍")
@RestController
public class BookController {

    @Autowired
    private BookService bookService;

    @PostMapping("/pms/book/create")
    public String create(@RequestBody BookDto dto) {
        Asserts.isFalse(bookService.create(dto), "添加书籍失败");
        return "添加书籍成功";
    }


    @GetMapping("/pms/book/delete/{id}")
    public String delete(@PathVariable Long id) {
        Asserts.isFalse(bookService.delete(id), "删除书籍失败");
        return "删除成功";
    }

    @PostMapping("/pms/book/down/{id}")
    public String down(@PathVariable Long id, @Validated
    @RequestParam(value = "state") @Range(max = 1, message = "修改的状态失败") Integer state) {
        Asserts.isFalse(bookService.updateState(id, state), "修改书籍上架状态失败");
        if (state == 1) {
            return "上架成功";
        }
        return "下架成功";
    }

    @PostMapping("/pms/book/update/{id}")
    public String update(@PathVariable Long id, @RequestBody @Validated BookDto dto) {
        Asserts.isFalse(bookService.update(id, dto), "更新失败");
        return "更新成功";
    }

    @GetMapping("/p/pms/book/list")
    public CommonPage<Book> list(
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "cateId", required = false) Long cateId,
            @RequestParam(value = "subId", required = false) Long subId,
            @RequestParam(value = "sort", defaultValue = "id") String orderBy,
            @RequestParam(value = "isAsc", defaultValue = "0") Integer isAsc,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum
    ) {
        Page<Book> page = bookService.list(keyword, cateId, subId, orderBy, isAsc, pageSize, pageNum);
        return CommonPage.restPage(page);
    }


}
